<template>
  <el-upload
      class="img-upload"
      ref="upload"
      action="'http://${window.location.hostname}:${window.location.port}/api/covers'"
      with-credentials
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="handleSuccess"
      multiple
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList">
    <span>点击上传</span>
  </el-upload>
</template>

<script>
export default {
  name: 'ImgUpload',
  data () {
    return {
      fileList: [],
      url: ''
    }
  },
  methods: {
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess (response) {
      if (response && response.url) {
        this.url = response.url
        this.$emit('onUpload', response)   // 把完整的 url 传给父组件
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败，服务器未返回 URL')
      }
    },
    clear () {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped>
.img-upload {
}
</style>
